use std::env;
use std::error::Error;
use std::fs;

pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
    let contents = fs::read_to_string(config.filename)?;
    let results = if config.case_insensitive {
        search(&config.query, &contents)
    } else {
        search_case_insensitive(&config.query, &contents)
    };
    for line in results {
        println!("{}", line);
    }
    Ok(())
}

pub struct Config {
    pub query: String,
    pub filename: String,
    pub case_insensitive: bool,
}

impl Config {
    pub fn new(mut args: std::env::Args) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("需要两个参数");
        }
        args.next();
        let query = match args.next() {
            Some(arg) => arg,
            None => return Err("没有得到要查询的值"),
        };
        let filename = match args.next() {
            Some(arg)=>arg,
            None=> return Err("没有得到要查询的文件"),
        };
        let case_insensitive = env::var("CASE_INSITIVE").is_err();
        Ok(Config {
            query,
            filename,
            case_insensitive,
        })
    }
}

pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    // let mut result = Vec::new();
    // for line in contents.lines() {
    //     if line.contains(query) {
    //         result.push(line);
    //     }
    // }
    // result
    contents.lines().filter(|line|line.contains(query)).collect()
}

pub fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
    // let mut result = Vec::new();
    // let query = query.to_lowercase();
    // for line in contents.lines() {
    //     if line.to_lowercase().contains(&query) {
    //         result.push(line);
    //     }
    // }
    // result
    contents.lines().filter(|line|{
        line.to_lowercase().contains(&query.to_lowercase())
    }).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn case_sensitive() {
        let query = "duct";
        let contents = "\
dust:
safe,face,production
Pick three;
Duct tap.
        ";
        assert_eq!(vec!["safe,face,production"], search(query, contents))
    }
    #[test]
    fn case_insensitive() {
        let query = "dUcT";
        let contents = "\
dust:
safe,face,production
Pick three;
Duct tap.
        ";
        assert_eq!(
            vec!["safe,face,production", "Duct tap."],
            search_case_insensitive(query, contents)
        )
    }
}
